<?php 
//闭包函数
$add = function (int $a, int $b) : int  {
    return $a + $b;
};

/**
 * 两数相乘函数 multi
 * @param int $a
 * @param int $b
 * @return int
 */
function multi(int $a, int $b) : int {
    return $a * $b;
}

$n1 = 1;
$n2 = 2;
$sum = $add($n1, $n2);
echo "$n1 + $n2 = $sum" . PHP_EOL;
var_dump($add);

$sum = call_user_func($add, $n1, $n2);
var_dump($sum);

echo '<br/>可变函数<br/>';
$add = 'multi';
$product = $add($n1, $n2);
echo "$n1 x $n2 = $product" . PHP_EOL;

//作用域
//计算两数相加
$add = function () use ($n1, $n2) {
    return $n1 + $n2;
};

//计算两数相乘
$multi = function () use ($n1, $n2){
    return $n1 * $n2;
};

//调用匿名函数
$sum = $add();
echo "$n1 + $n2 = $sum" . '<br/>';
$product = $multi();
echo "$n1 x $n2 = $product" . '<br/>';

//global
//计算两数相减
function sub () {
    global $n1, $n2;
    return $n1 - $n2;
}
$sub = sub();
echo "$n1 - $n2 = $sub" . '<br/>';

//global对比匿名函数
function add1($n1, $n2) {
    return function () use ($n1, $n2) {
        return $n1 + $n2;
    };
}

function add2() {
    return function () {
        global $n1, $n2, $n3;
        return $n1 + $n2 +$n3;
    };
}

$n1 = 1;
$n2 = 3;
$n3 = 4;
$add =add1($n1, $n2);
$sum = $add();
echo "$n1 + $n2 = $sum" . '<br/>';

$add = add2();
$sum = $add();
echo "$n1 + $n2 + $n3 = $sum" . '<br/>';

//global安全调用
 function test()
{
    printf("n1 = %d, n2 = %d, n3 = %d", $GLOBALS['n1'], $GLOBALS['n2'], $GLOBALS['n3']);
}
test();